﻿using System;
using System.Collections.Generic;
using System.Text;
using StockTrader.DAL.HnxMonitor.DataAccess;
using System.Windows.Forms;
using System.Drawing;

namespace StockTrader.DAL.HnxMonitor.BusinessLogic
{
    class AsyncProcessor
    {
        DALclient client = new DALclient();
        private UpdateDB _invokeMe;
        private Label _lblState;
        private string _objType;

        private delegate string UpdateDB();

        public AsyncProcessor(Label lblState, string objType)
        {
            _lblState = lblState;
            _objType = objType;
            switch (objType)
            {
                case "Orders":
                    _invokeMe = new UpdateDB(DataEngine.ProcessOrders);
                    break;
                case "MarketInfo":
                    _invokeMe = new UpdateDB(DataEngine.ProcessMarketInfo);
                    break;
                case "StockInfo":
                    _invokeMe = new UpdateDB(DataEngine.ProcessStockInfo);
                    break;
                case "TopPrice":
                    _invokeMe = new UpdateDB(DataEngine.ProcessTopPrice);
                    break;
                case "Initialize":
                    _invokeMe = new UpdateDB(DataEngine.Initialize);
                    break;
            }

        }

        public void Execute()
        {
            //Update UI here
            MethodInvoker updateUIState = delegate
            {
                _lblState.BackColor = Color.Red;
            };
            if (_lblState.InvokeRequired)
                _lblState.Invoke(updateUIState);
            else
                updateUIState();
            _invokeMe.BeginInvoke(this.CallBack, null);

        }
        private void CallBack(IAsyncResult ar)
        {
            try
            {
                string listCount = _invokeMe.EndInvoke(ar);
                //Update UI here
                MethodInvoker updateUIState = delegate
                {
                    _lblState.Text = listCount;
                    if (ar.IsCompleted)
                        _lblState.BackColor = Color.Green;
                };
                if (_lblState.InvokeRequired)
                    _lblState.Invoke(updateUIState);
                else
                    updateUIState();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }


    }
}
